﻿#include <QSerialPortInfo>
#include "widgetserialportcfg.h"
#include "ui_widgetserialportcfg.h"
#include "commconfig.h"
#include "serialportwrap.h"

WidgetSerialPortCfg::WidgetSerialPortCfg(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::WidgetSerialPortCfg)
{
    ui->setupUi(this);
}

WidgetSerialPortCfg::~WidgetSerialPortCfg()
{
    delete ui;
}

void WidgetSerialPortCfg::setComm(BaseCommunication *comm)
{
    _comm=comm;

    ui->cmbBaudRate->clear();
    QStringList baudRates={"4800","9600","19200","38400"};
    ui->cmbBaudRate->addItems(baudRates);

    ui->cmbDataBits->clear();
    ui->cmbDataBits->addItems(SerialPortWrap::getDataList());

    ui->cmbParityCom->clear();
    ui->cmbParityCom->addItems(SerialPortWrap::getParityList());

    ui->cmbStopBit->clear();
    ui->cmbStopBit->addItems(SerialPortWrap::getStopList());

    ui->cmbFlowControl->clear();
    ui->cmbFlowControl->addItems(SerialPortWrap::getFlowList());

    updateSerialPort();

    loadConfig();
}

QStringList WidgetSerialPortCfg::getAvailablePortsString()
{
    QList<QSerialPortInfo> availablePorts=QSerialPortInfo::availablePorts();
    QStringList ret;
    for(auto item:availablePorts)
    {
        ret.append(item.portName());
    }
    return ret;
}

void WidgetSerialPortCfg::loadConfig()
{
    CommConfig &appCfg=CommConfig::instance();
    SerialPortParam sp=appCfg.getSerialPortCfg(_comm->name());
    QStringList pn=getAvailablePortsString();
    if(pn.contains(sp.comName))
    {
        ui->cmbPortName->setCurrentText(sp.comName);
    }
    ui->cmbBaudRate->setCurrentText(sp.baudRate);
    ui->cmbDataBits->setCurrentText(sp.dataBits);
    ui->cmbParityCom->setCurrentText(sp.parity);
    ui->cmbStopBit->setCurrentText(sp.stopBits);
    ui->cmbFlowControl->setCurrentText(sp.flowControl);
}

void WidgetSerialPortCfg::on_openSerial_clicked()
{
    SerialPortParam sp;
    sp.comName=ui->cmbPortName->currentText();
    sp.baudRate=ui->cmbBaudRate->currentText();
    sp.dataBits=ui->cmbDataBits->currentText();
    sp.stopBits=ui->cmbStopBit->currentText();
    sp.parity=ui->cmbParityCom->currentText();
    sp.flowControl=ui->cmbFlowControl->currentText();
    QJsonObject obj={
        {"address",sp.comName},
        {"baud_rate",sp.baudRate.toInt()},
        {"data_bits",sp.dataBits},
        {"stop_bits",sp.stopBits},
        {"parity",sp.parity},
    };
    _comm->setConfig(obj);
    if(_comm->connectToHost())
    {
        ui->openSerial->setEnabled(false);
        CommConfig::instance().setSerialPortCfg(_comm->name(),sp);
    }
}

void WidgetSerialPortCfg::on_closeSerial_clicked()
{
    _comm->disConnect();
    ui->openSerial->setEnabled(true);
}

void WidgetSerialPortCfg::on_btnUpdataSerialPort_clicked()
{
    updateSerialPort();
}

void WidgetSerialPortCfg::updateSerialPort()
{
    QStringList availablePorts =getAvailablePortsString();
    ui->cmbPortName->clear();
    ui->cmbPortName->addItems(availablePorts);
}
